<template>
    <el-container class="layout-container">
        <!-- 全屏遮罩 -->
        <div v-if="showLoading" class="overlay">
            <div class="loading-spinner"></div>
        </div>
        <!-- 使用公共侧边栏组件 -->
        <CommonSidebar />


        <el-container class="container">
            <el-aside class="aside">
                <div class="examples-section">
                    <h3>AI绘图</h3>
                    <div class="examples">
                        <div class="example-card" v-for="(example, index) in examples" :key="index"
                            @click="useExample(example)">
                            <img :src="example.image" class="example-image" />
                            <div class="example-desc">{{ example.desc }}</div>
                        </div>
                    </div>
                </div>
                <el-form :model="form" label-width="auto" style="min-width: 460px" class="form-content">
                    <h4>创意描述</h4>
                    <div class="form-input">
                        <textarea class="form-textarea" v-model="textContent" rows="4" placeholder="请输入创意描述"></textarea>
                        <div class="input-tools">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-infinity"></use>
                            </svg>
                            <button type="button" @click="handleAIHelp">
                                帮我写 </button>
                            <div class="input-tools-right">
                                {{ textLength }}/400
                                <button type="button" @click="clearText">清空</button>
                            </div>

                        </div>
                    </div>
                    <div class="reference">
                        <div class="upload-section">
                            <div class="reference-text">上传参考图</div>
                            <el-upload action="/api/upload" :show-file-list="false" accept="image/*"
                                :before-upload="beforeUploadReference" :on-success="handleReferenceSuccess">
                                <div class="reference-area" v-if="!referenceImage">
                                    <svg class="icon" aria-hidden="true">
                                        <use xlink:href="#icon-shangchuan"></use>
                                    </svg>
                                </div>
                                <!-- <img src="http://192.168.1.123:8124/static/output/ComfyUI_00001_.png" class="reference-preview"> -->
                                <img v-else :src="referenceImage" class="reference-preview">
                            </el-upload>
                        </div>
                        <div class="reference-size">
                            <div class="radio-size" v-for="size in sizes" :key="size.id"
                                :class="{ active: currentSize === size.id }" @click="handleSizeSelect(size)">
                                {{ size.text }}
                            </div>
                        </div>
                    </div>

                    <el-button type="primary" class="btn" @click="createImage" :loading="showLoading">
                        {{ showLoading ? '生成中...' : '生成图片' }}
                    </el-button>

                </el-form>

            </el-aside>
            <el-main class="main">
                <div class="image-container">
                    <template v-if="generatedImage">
                        <el-image-viewer v-if="showViewer" :url-list="[generatedImage]" :initial-index="0"
                            @close="closeViewer" />
                        <img :src="generatedImage" class="previewImage" alt="生成的图片" @click="openViewer">
                        <div class="image-actions">
                            <el-button style="background-color: #409EFF; color: white;" @click="downloadImage"
                                :icon="Download">
                                下载图片
                            </el-button>
                        </div>
                    </template>
                </div>
            </el-main>

        </el-container>
    </el-container>
</template>

<script setup>
import { onMounted, reactive, ref, onActivated, computed } from 'vue'
import { useImagesStore } from '@/store/modules/images';
import beachImage from '../assets/beach.png'
import girlImage from '../assets/girl.png'
import gardenImage from '../assets/garden.png'
import fotado from '../assets/fotado.png';
import sciencfkcio from '../assets/sciencfikcio.png';
import Teksturo from '../assets/Teksturo.png';
import { ElImageViewer } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
const ImagesStore = useImagesStore()

const textContent = ref('')

const showLoading = ref(false)

const textLength = computed(() => {
    return textContent.value.length
})

// Clear text function
const clearText = () => {
    textContent.value = ''
}

// AI help function
const handleAIHelp = () => {
    // TODO: Implement AI writing assistance
    ElMessage.info('AI写作助手即将上线')
}

// 添加参考图相关变量
const referenceImage = ref('')
const currentSize = ref('1080p')
const sizes = ref([
    { id: '1080p', text: '1080P', width: 1920, height: 1080 },
    { id: '720p', text: '720P', width: 1280, height: 720 },
    { id: '640p', text: '640P', width: 640, height: 480 },
    { id: '1:1', text: '1:1', width: 1024, height: 1024 },
    { id: '4:3', text: '4:3', width: 1024, height: 768 },
    { id: '3:4', text: '3:4', width: 768, height: 1024 },
])

const handleSizeSelect = (size) => {
    currentSize.value = size.id
    form.width = size.width
    form.height = size.height
}

// 添加参考图上传方法
const beforeUploadReference = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 20

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

const handleReferenceSuccess = (res, file) => {
    const originalName = file.name


    referenceImage.value = `http://192.168.1.13:8124/static/input/${originalName}`

    console.log(referenceImage.value)

    ElMessage.success('参考图上传成功')
}

const examples = ref([
    {
        image: beachImage,
        desc: 'CG',
        style: 'LLM'
    },
    {
        image: girlImage,
        desc: '动漫',
        style: '基础'
    },
    {
        image: gardenImage,
        desc: '油画',
        style: 'good'
    },
     {
        image: fotado,
        desc: '摄影',
        style: 'LLM'
    },
    {
        image: sciencfkcio,
        desc: '科幻',
        style: '基础'
    },
    {
        image: Teksturo,
        desc: '自然',
        style: 'good'
    },
])

// userStore.fetchUserInfo()

// 点击示例时填充表单
const useExample = (example) => {
    form.style = example.style
}

const form = reactive({
    style: 'LLM',
    width: 1920,
    height: 1080
})


const generatedImage = ref(beachImage)

const createImage = async () => {
    if (!textContent.value.trim()) {
        ElMessage.warning('请输入图片描述')
        return
    }
    showLoading.value = true
    
    // Extract filename from referenceImage URL if it exists
    const imgFileName = referenceImage.value
        ? referenceImage.value.split('/').pop()
        : '';

    console.log(imgFileName)
    const requestParams = {
        desc: textContent.value,
        ...form,
        style: referenceImage.value ? '图生图' : form.style,
        img: imgFileName
    }
    try {
        await ImagesStore.fetchEncodedImages(requestParams)
        // 这里添加调用AI生成图片的API
        const { image } = ImagesStore.encodedImages
        generatedImage.value = image
        // 保存图片到缓存
        saveImageTocache(image)
    } catch (error) {
        console.log(error)
        ElMessage.error('生成图片失败')
    } finally {
        showLoading.value = false
    }
}

const saveImageTocache = (img) => {
    sessionStorage.setItem('cachedGeneratedImage', img)
}

const loadImageFromCache = () => {
    const cachedImage = sessionStorage.getItem('cachedGeneratedImage')
    if (cachedImage) {
        generatedImage.value = cachedImage
    }
}

const downloadImage = () => {
    if (!generatedImage.value) {
        ElMessage.warning('请先生成图片')
        return
    }
    // 直接创建下载链接
    const link = document.createElement('a')
    link.href = generatedImage.value
    link.download = `linglong-ai-${Date.now()}.png`

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('图片下载成功')
}

// 控制查看器显示状态
const showViewer = ref(false)

// 添加查看器控制方法
const openViewer = () => {
    if (generatedImage.value) {
        showViewer.value = true
    }
}

const closeViewer = () => {
    showViewer.value = false
}

onMounted(() => {
    const cachedImage = loadImageFromCache()
    if (cachedImage) {
        generatedImage.value = cachedImage
    }
})

</script>

<style scoped>
.layout-container {
    height: 100vh;
    display: flex;
}

.container {
    flex: 1;
    background-color: #f5f7fa;
    min-width: 1400px;
    min-height: 700px;
    overflow-x: auto;
    background: linear-gradient(135deg, #f5f7fa, #f0f2f5);
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999; /* 确保遮罩层位于最上层 */
}

/* 加载动画样式 */
.loading-spinner {
  border: 8px solid #f3f3f3;
  border-top: 8px solid #3498db;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 1s linear infinite;
}

/* 旋转动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.aside {
    background-color: #fff;
    border-right: 1px solid #eee;
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;
    min-width: 500px;
    overflow: hidden;
}

.examples-section {
    width: 460px;
}

.examples-section h3 {
    margin-bottom: 14px;
    margin-left: 20px;
    color: #333;
    font-size: 20px;

}

.examples {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-evenly;
}

.example-card {
    cursor: pointer;
    text-align: center;
    position: relative;
    margin: 0 0 12px 0;
    width: 135px;
    height: 110px;
    border-radius: 10px;
    overflow: hidden;
}

.example-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: all 0.3s;
}

.example-image:hover {
    transform: scale(1.1);
}

.example-desc {
    position: absolute;
    bottom: 0;
    font-size: 13px;
    padding: 5px 10px 5px 10px;
    width: 100%;
    box-sizing: border-box;
    background: rgba(37, 36, 36, 0.3);
    backdrop-filter: blur(10px);
    color: #fff;
    text-align: center;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
}

.form-content {
    display: flex;
    flex-direction: column;
}

.form-content h4 {
    font-size: 15px;
    margin: 0 0 10px 10px;
}

.form-input {
    background-color: #eee;
    padding: 20px 20px 0 20px;
    box-sizing: border-box;
    height: 130px;
    margin-bottom: 10px;
    border-radius: 8px;
    width: 100%;
    border: 1px solid transparent;
    transition: all 0.3s ease;
}

.form-input:hover,
.form-input:focus-within {
    border-color: #409EFF;
}

.form-textarea {
    background-color: #eee;
    border: 0px;
    width: 420px;
    font-size: 13px;
    resize: none;
    overflow: auto;
    margin-bottom: 5px;
    color: black;
}

.form-textarea:focus {
    border: none;
    outline: none;
}

.input-tools {
    color: #666;
    border-top: 1px solid #ddd;
    padding-top: 8px;
    display: flex;
    font-size: 13px;
    justify-content: space-between;
    align-items: center;
}

.input-tools .icon {
    width: 15px;
    height: 15px;

}



.input-tools button {
    color: #666;
    padding-left: 0;
    font-weight: bold;
    background-color: #eee;
    font-size: 12px;
    border: 0;
    margin-right: 275px;
}

.input-tools-right button {
    font-weight: normal;
    margin-left: 10px;
    margin-right: 0;
    padding-right: 0;
}

.reference {
    display: flex;
    width: 100%;
    height: 100px;
    justify-content: space-between;
}

.upload-section {
    width: 200px;
    box-sizing: border-box;
    padding: 10px;
    background: #eee;
    border-radius: 8px;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.reference-text {
    font-size: 14px;
    color: #333;
}

.reference-area {
    width: 75px;
    height: 75px;
    border-radius: 8px;
    background-color: #fff;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
}

.reference-area:hover {
    box-shadow: #ccc 0 0 5px;
}

.reference-area .icon {
    width: 25px;
}

.reference-preview {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 8px;
    cursor: pointer;
    transition: transform 0.2s;
}

.reference-size {
    width: 260px;
    height: 100px;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-evenly;
}


.radio-size {
    height: 40px;
    background-color: #eee;
    width: 80px;
    border-radius: 8px;
    text-align: center;
    line-height: 40px;
    transition: all 0.3s ease;
    font-size: 13px;
}

.radio-size:not(.active):hover {
    background-color: #e0e0e0;
}

.active {
    background-color: rgba(64, 158, 255, 0.15);
    color: #409EFF;
    font-weight: 500;
}

.previewImage {
    cursor: zoom-in;
    transition: transform 0.2s;
}

.main {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    flex: 1;
}

.image-container {
    width: 100%;
    max-width: 800px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    position: relative;
    margin: 0 auto;
}

.previewImage {
    width: 100%;
    height: 100%;
    object-fit: contain;
    border-radius: 8px;
}

.btn {
    display: block;
    width: 180px;
    height: 40px;
    margin: 20px auto;
    font-size: 16px;
    font-weight: 500;
    letter-spacing: 1px;
    background: linear-gradient(45deg, #409EFF, #36cfc9);
    border: none;
    transition: transform 0.2s;
}

.btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.image-actions {
    position: absolute;
    bottom: -60px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 10px;
    background-color: rgba(255, 255, 255, 0.9);
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
